
#include <string.h>

#include "xota+crypto.h"
#include "md5.h"
#include "crc32.h"



// const uint8_t md5_key[16] = {0x4A, 0x28, 0x7C, 0x81, 0x12, 0x86, 0x62, 0x1C, 0xB8, 0x58, 0xDA, 0x9E, 0x94, 0x8B, 0x36, 0xBA}; 
const uint8_t md5_key[16] = {0xCE, 0x95, 0x39, 0xB8, 0xEB, 0xF6, 0x39, 0x25, 0x0D, 0xA9, 0x81, 0x40, 0xCF, 0xCE, 0xCC, 0x98};



/**@brief compute md5 
 * @data data to be compute 
 * @len  lenght of data to compute
 * @hash result output
 * @return result length
 */  
int xota_crypto_compute_md5( uint8_t * data, uint32_t len, uint8_t* hash)
{
    MD5_CTX md5;
    MD5Init( &md5 );    
    
    MD5Update( &md5, data, len);    
    
    MD5Final( &md5, hash );

    return 16; 
}



int xota_crypto_sign_verify( uint8_t *hash, uint32_t len, uint8_t * sig)
{
    uint8_t sig_cal[16];

    MD5_CTX md5;
    MD5Init( &md5 );
    
    MD5Update( &md5, (uint8_t*)md5_key, 16);
    MD5Update( &md5, hash, len);

    MD5Final( &md5, sig_cal );

    return memcmp( sig_cal, sig, len);
}

uint32_t xota_crypto_crc32_compute( uint8_t * data, uint32_t len)
{
    uint8_t * p_src = data; 
    uint32_t crc32 = 0; 

//    if( data == 0) //stupid mechanism when address is 0(NULL)
//    {
//        uint8_t temp[256];
//        uint32_t start_address = 0; 
//        uint32_t chunk_len = 0; 
//        while( start_address < len)
//        {
//            chunk_len = len - start_address;
//            if( chunk_len > 256){
//                chunk_len = 256;
//            }
////            pf_flash_read_page(start_address, temp, chunk_len);
//            crc32 = crc32_compute( temp, chunk_len, &crc32 );
//            start_address += 256;
//        }
//    }
//    else
    {
        crc32 = crc32_compute( p_src, len, NULL );
    }

    return crc32; 
}
